package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.dto.ProjectNewDynamicDto;
import cn.com.cifi.mars.bean.dto.ProjectToDoDto;
import cn.com.cifi.mars.bean.dto.SysToDoDto;
import cn.com.cifi.mars.bean.vo.common.CommonVo;
import cn.com.cifi.mars.bean.vo.sys.rsp.StagesVo;
import cn.com.cifi.mars.bean.vo.workBench.ProjectNewDynamicVo;
import cn.com.cifi.mars.bean.vo.workBench.ProjectToDoVo;
import cn.com.cifi.mars.bean.vo.workBench.SysToDoVo;
import cn.com.cifi.mars.constant.*;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.entity.common.ProjectByStages;
import cn.com.cifi.mars.mapper.mars.*;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.WorkBenchService;
import cn.com.cifi.mars.util.StrUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作台
 * @author Li
 *
 */
@Slf4j
@Service
public class WorkBenchServiceImpl implements WorkBenchService {

	@Autowired
	private ProjectByStagesMapper projectByStagesMapper;
	@Autowired
	private PortalTodoMapper portalTodoMapper;
	@Autowired
	private VersionLogMapper versionLogMapper;
	@Autowired
	private IdmUserService idmUserService;
	@Autowired
	private ProjectMapper projectMapper;
	@Autowired
	private IdmUserMapper idmUserMapper;
	
	/**
	 * 根据项目id,显示分期下拉框
	 */
	@Override
	public List<StagesVo> queryStagesList(String projectId) {
		List<StagesVo>list=new ArrayList<>();
		//根据项目id查询所有分期
		list=projectByStagesMapper.selectStagesVoList(projectId,HrOrgTypeEunm.ORG_32.getKey());
		StagesVo vo=new StagesVo();
		//0
		vo.setStagesId(Constants.ZERO+"");
		//全部分期
		vo.setStagesName(Constants.ALL_STAGES);
		list.add(0,vo);
		return list;
	}

	/**
	 * 显示门户待办类型(下拉框)
	 */
	@Override
	public List<CommonVo> getTodoType() {
		List<CommonVo> list=new ArrayList<>();
		CommonVo vo=new CommonVo();
		//0
		vo.setCode(Constants.ZERO+"");
		//全部
		vo.setName(Constants.ALL);
		list.add(0,vo);
		for (TodoTypeCodeEnum v : TodoTypeCodeEnum.values()) {
			CommonVo c=new CommonVo();
			c.setCode(v.getKey());
			c.setName(v.getValue());
			list.add(c);
		}
		return list;	
	}

	/**
    * 项目待办提醒分页
    * @param current 当前第几页
    * @param pageSize 每页条数
    * @param projectId 项目id
    * @param stagesId 分期id
    * @param typeId 类型id
    * @param state 处理状态
    * @return
    */
	@Override
	public ProjectToDoVo getPorjectToDoPage(String current, String pageSize, String projectId, String stagesId,
			String typeId, String state) {
		ProjectToDoVo vo = new ProjectToDoVo();
		Page<ProjectToDoVo> pageDto = new Page<>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		List<ProjectToDoDto> list = portalTodoMapper.selectPorjectToDoList(pageDto,projectId,stagesId,typeId,state);
		if(CollectionUtils.isNotEmpty(list)) {
			list.forEach(x->{
				//待办类型
				String todoTypeCode=x.getTodoTypeCode();
				String todoTypeName=TodoTypeCodeEnum.getValueByKey(todoTypeCode);
				x.setTodoTypeName(todoTypeName);
				//待办事项状态
				String todoStatus=x.getTodoStatus();
				String todoStatusName=TodoStatusEnum.getValueByKey(todoStatus);
				x.setTodoStatusName(todoStatusName);
				String orgType=x.getOrgType();
				if(StringUtils.isNotEmpty(orgType)) {
					//待办组织类型 1 旭辉集团 2 区域或事业部 3 城市公司 4 项目 5分期
					if(orgType.equals(TodoOrgTypeEnum.FOUR.getKey())) {
						//项目分期：显示具体项目名称
						x.setProjectStages(x.getProjectName());
					}
					if(orgType.equals(TodoOrgTypeEnum.FIVE.getKey())) {
						// 项目分期：显示具体项目分期名称
						x.setProjectStages(x.getProjectName()+x.getStagesName());
					}
				}

				//处理货值区域为空问题
				if (StringUtils.isNotEmpty(todoTypeCode) && todoTypeCode.equals(TodoTypeCodeEnum.PRICE_VALUE.getKey())){
					List<ProjectByStages> parentList = projectMapper.selectParentData(projectId);
					String businessId="";
					String cityId="";
					if(org.apache.commons.collections.CollectionUtils.isNotEmpty(parentList)) {

						for(ProjectByStages obj : parentList) {
							String typeOrgId = obj.getHrOrgTypeId();
							if(typeOrgId.equals(HrOrgTypeEunm.ORG_11.getKey())) {
							}else if(typeOrgId.equals(HrOrgTypeEunm.ORG_21.getKey())) {
								cityId = obj.getOrgdepid();
						 	}else if(typeOrgId.equals(HrOrgTypeEunm.ORG_20.getKey())) {
								businessId = obj.getOrgdepid();
							}
						}
					}
					String pcTaskUrl = x.getPcTaskUrl();
					for (int i=0;i<3;i++){
						pcTaskUrl = pcTaskUrl.substring(0, pcTaskUrl.lastIndexOf("/"));
					}
					pcTaskUrl = pcTaskUrl+"/"+businessId+"/"+cityId+"/"+projectId;
					x.setPcTaskUrl(pcTaskUrl);
				}
			});
		}
		
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}

	/**
    * 系统待办提醒分页
    * @param current 当前第几页
    * @param pageSize 每页条数
    * @param nameOrCode 项目名称或者项目编码
    * @param typeId 类型id
    * @param state 处理状态
    * @return
    */
	@Override
	public SysToDoVo getSysToDoPage(String current, String pageSize, String nameOrCode, String typeId, String state,String userId) {
		SysToDoVo vo = new SysToDoVo();
		Page<SysToDoVo>pageDto=new Page<>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		//查询系统待办提醒分页
		List<SysToDoDto>list=new ArrayList<>();
		List<ProjectByStagesDto> projectByStagesDtoList = idmUserService.queryUserDataPermissions(userId);
		List<String>projectIds = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(projectByStagesDtoList)) {
			projectIds = projectByStagesDtoList.stream().map(x-> x.getOrgdepid()).collect(Collectors.toList());
			list=portalTodoMapper.selectSysToDoList(pageDto,nameOrCode,typeId,state,projectIds);
		}
		
		if(CollectionUtils.isNotEmpty(list)) {
			list.forEach(x->{
				//待办类型
				String todoTypeCode=x.getTodoTypeCode();
				String todoTypeName=TodoTypeCodeEnum.getValueByKey(todoTypeCode);
				x.setTodoTypeName(todoTypeName);
				//待办事项状态
				String todoStatus=x.getTodoStatus();
				String todoStatusName=TodoStatusEnum.getValueByKey(todoStatus);
				x.setTodoStatusName(todoStatusName);
				String orgType=x.getOrgType();

				//处理货值区域为空问题
				if (StringUtils.isNotEmpty(todoTypeCode) && todoTypeCode.equals(TodoTypeCodeEnum.PRICE_VALUE.getKey())){
					List<ProjectByStages> parentList = projectMapper.selectParentData(x.getProjectId());
					String groupName="";
					String businessId="";
					String businessName = "";
					String cityId="";
					String cityName="";
					if(org.apache.commons.collections.CollectionUtils.isNotEmpty(parentList)) {

						for(ProjectByStages obj : parentList) {
							String typeOrgId = obj.getHrOrgTypeId();
							if(typeOrgId.equals(HrOrgTypeEunm.ORG_11.getKey())) {
								groupName = obj.getOrgname();
							}else if(typeOrgId.equals(HrOrgTypeEunm.ORG_21.getKey())) {
								cityId = obj.getOrgdepid();
								cityName = obj.getOrgname();
							}else if(typeOrgId.equals(HrOrgTypeEunm.ORG_20.getKey())) {
								businessId = obj.getOrgdepid();
								businessName = obj.getOrgname();
							}
						}
					}
					x.setGroupName(groupName);
					x.setRegionName(businessName);
					x.setCityName(cityName);
					String pcTaskUrl = x.getPcTaskUrl();
					for (int i=0;i<3;i++){
						pcTaskUrl = pcTaskUrl.substring(0, pcTaskUrl.lastIndexOf("/"));
					}
					pcTaskUrl = pcTaskUrl+"/"+businessId+"/"+cityId+"/"+x.getProjectId();
					x.setPcTaskUrl(pcTaskUrl);
				}

				if(StringUtils.isNotEmpty(orgType)) {
					//待办组织类型 1 旭辉集团 2 区域或事业部 3 城市公司 4 项目 5分期
					if(orgType.equals(TodoOrgTypeEnum.ONE.getKey())) {
				        //集团待办：
						//区域：显示“旭辉集团”；
						x.setRegionName(Constants.GROUP_NAME);
						//城市公司/项目/分期：显示空；
//						x.setCityProjectStages(x.getGroupName());
					}
					/*if(orgType.equals(TodoOrgTypeEnum.TWO.getKey())) {
//					        区域待办：
//					        区域：显示具体区域名称；
//					        城市公司/项目/分期：显示空；
						x.setCityProjectStages(x.getRegionName());
					}
					if(orgType.equals(TodoOrgTypeEnum.THREE.getKey())) {	
//					        城市公司待办：
//					        区域：显示具体区域名称；
//					        城市公司/项目/分期：显示具体城市公司名称；
						x.setCityProjectStages(x.getCityName());
					}
					if(orgType.equals(TodoOrgTypeEnum.FOUR.getKey())) {
//					        项目待办：
//					        区域：显示具体区域名称；
//					        城市公司/项目/分期：显示具体项目名称；
						x.setCityProjectStages(x.getProjectName());
					}
					if(orgType.equals(TodoOrgTypeEnum.FIVE.getKey())) {
//					        项目分期待办：
//					        区域：显示具体区域名称；
//					        城市公司/项目/分期：显示具体项目分期名称；
						x.setCityProjectStages(x.getProjectName()+x.getStagesName());
					}*/
				}
			});
		}
		
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}

   /**
    * 项目最新动态
    * @param current 当前第几页
    * @param pageSize 每页条数
    * @param projectId 项目id
    * @param stagesId 分期id
    * @param eventId 事件id
    * @param versionType 版本类型
    * @param operationBy 操作人
    * @param begin 开始时间
    * @param end 结束时间
    * @return
    */
	@Override
	public ProjectNewDynamicVo getProjectNewDynamicPage(String current, String pageSize, String projectId,
			String stagesId, String eventId, String moduleTypeId, String versionType, String operationBy,
			String begin, String end) {
		ProjectNewDynamicVo vo=new ProjectNewDynamicVo();
		String versionTypeName = VersionTypeEunm.getValueByKey(versionType);
		Page<ProjectNewDynamicVo>pageDto=new Page<>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		List<ProjectNewDynamicDto>list= versionLogMapper.selectProjectNewDynamicList(pageDto,
				  projectId,stagesId,eventId,moduleTypeId,versionTypeName,operationBy, begin,end,IsDelayEnum.NO.getKey()+"");

		Set<String> usercnList = Optional.of(list).orElseGet(ArrayList::new)
				.stream().map(ProjectNewDynamicDto::getOperationBy)
				.collect(Collectors.toSet());
		List<IdmUser> userList = new ArrayList<IdmUser>();
		Map<String, IdmUser> userMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(usercnList)){
			QueryWrapper<IdmUser> userWrapper = new QueryWrapper<IdmUser>();
			userWrapper.in("alias", usercnList);
			userList = idmUserMapper.selectList(userWrapper);
			if (CollectionUtils.isNotEmpty(userList)){
				userMap = userList.stream().collect(Collectors.toMap(IdmUser::getAlias, a -> a,(k1,k2)->k1));
			}
		}

		if(CollectionUtils.isNotEmpty(list)) {
			Map<String, IdmUser> finalUserMap = userMap;
			list.forEach(x->{
				//操作人
				String alias=x.getOperationBy();
				if(StrUtils.isNotEmpty(alias) && alias.equals(Constants.SYS)) {
					x.setUsercn(Constants.SYS_NAME);
				}else {
					//x.setUsercn(getUsercn(alias,userList));
					x.setUsercn((finalUserMap.get(alias))==null?"": finalUserMap.get(alias).getUsercn());
				}
				//事件
				if(StrUtils.isNotEmpty(x.getEvent())) {
					String click_value=VersionEventEnum.getKeyByValue(x.getEvent());
					x.setEvent(click_value);
				}
				//业务类型
				String moduleTypeValue=ModuleTypeEunm.getValueByKey(x.getModuleType());
				x.setModuleTypeName(moduleTypeValue);

				//操作前状态
				if(StringUtils.isNotBlank(x.getBeforeState())) {
					String beforeValue=VersionStatusEnum.getValueByKey(x.getBeforeState());
					x.setBeforeState(beforeValue);
				}
				//操作后状态
				if(StringUtils.isNotBlank(x.getAfterState())) {
					String afterValue=VersionStatusEnum.getValueByKey(x.getAfterState());
					x.setAfterStateValue(afterValue);
				}
			});
		}
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}

	private String getUsercn(String alias, List<IdmUser> userList) {
		if(CollectionUtils.isNotEmpty(userList)) {
			for(IdmUser user : userList) {
				if(StrUtils.isNotEmpty(alias) && alias.equals(user.getAlias())) {
					return user.getUsercn();
				}
			}
		}
	return "";
}

	/**
	 * 事件(下拉框)
	 */
	@Override
	public List<CommonVo> getEvent() {
		List<CommonVo> list=new ArrayList<>();
		CommonVo vo=new CommonVo();
		//0
		vo.setCode(Constants.ZERO+"");
		//全部
		vo.setName(Constants.ALL);
		list.add(0,vo);
		for (VersionEventEnum v : VersionEventEnum.values()) {
			CommonVo c=new CommonVo();
			c.setCode(v.getKey());
			c.setName(v.getValue());
			list.add(c);
		}
		return list;
	}
	
	/**
	 * 业务类型(下拉框)
	 */
	@Override
	public List<CommonVo> getBusinessType() {
		List<CommonVo> list=new ArrayList<>();
		CommonVo vo=new CommonVo();
		//0
		vo.setCode(Constants.ZERO+"");
		//全部
		vo.setName(Constants.ALL);
		list.add(0,vo);
		for (ModuleTypeEunm v : ModuleTypeEunm.values()) {
			CommonVo c=new CommonVo();
			c.setCode(v.getKey());
			c.setName(v.getValue());
			list.add(c);
		}
		return list;
	}
	
	/**
	 * 版本类型(下拉框)
	 */
	@Override
	public List<CommonVo> getVersionType() {
		List<CommonVo> list=new ArrayList<>();
		CommonVo vo=new CommonVo();
		//0
		vo.setCode(Constants.ZERO+"");
		//全部
		vo.setName(Constants.ALL);
		list.add(0,vo);
		
		//循环枚举的值
		for (VersionStageEunm v : VersionStageEunm.values()) {
			CommonVo c=new CommonVo();
			c.setCode(v.getKey());
			c.setName(v.getValue());
			list.add(c);
		}
		return list;
	}
	
	/**
	 * 操作人(下拉框)
	 */
	@Override
	public List<CommonVo> getOperationBy(String projectId) {
		List<CommonVo> res = Collections.synchronizedList(new ArrayList<>());
		//查询操作人
		List<Map<String, Object>> list = versionLogMapper.selectOperationByList(projectId);
		if(CollectionUtils.isNotEmpty(list)) {
			for(Map<String, Object> map : list) {
				if(map != null && !map.isEmpty()) {
					String code = String.valueOf(map.get("operation_by"));
					String name = String.valueOf(map.get("usercn"));
					if(StrUtils.isNotEmpty(code)) {
						if(code.equals(Constants.SYS)) {
							name = Constants.SYS_NAME;
						}
						CommonVo vo = new CommonVo();
						vo.setCode(code);
						vo.setName(name);
						res.add(vo);
					}
				}
			}
		}
		return res;
	}
	
}
